package com.zkrt.upms.common.component;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zkrt.upms.common.util.HJ212Util;
import com.zkrt.upms.common.util.SocketUtil;
import com.zkrt.upms.dto.IdentityDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 上传服务
 */
@Component
@Slf4j
public class UploadService {

    @Value("${sendtask.api.address}")
    private String apiAddress;

    @Value("${sendtask.api.action.generatekey}")
    private String generateKeyAction;

    @Value("${sendtask.api.action.getentitys}")
    private String getEntitysAction;

    @Value("${sendtask.upload.dataserver.host}")
    private String host;

    @Value("${sendtask.upload.dataserver.port}")
    private Integer port;

    private static int keyCount = 0;
    private final int keyMax = 6;
    private String count4GenerateKey() throws Exception {
        if (keyCount >= keyMax) {
            keyCount = 0;
            log.error("[超出最大鉴权请求次数] -> 单次请求上限：{}", keyMax);
            return null;
        }
        ++keyCount;
        log.warn("[鉴权失败] -> {}次", keyCount);
        Thread.sleep(3000);
        return generateKey();
    }

    /**
     * 获取AuthorizationKey
     * @return
     */
    private String generateKey() {
        if (ObjectUtil.isEmpty(apiAddress)) {
            log.error("[无接口地址]");
            return null;
        }
        String identity = MD5.create().digestHex16(String.valueOf(Math.random()));
        String token = MD5.create().digestHex(String.valueOf(Math.random()));
        IdentityDTO request = new IdentityDTO();
        request.setIdentity(identity);
        request.setToken(token);
        try {
            String response = HttpRequest.post(new StringBuffer(apiAddress).append(generateKeyAction).toString())
                    .body(JSON.toJSONString(request)).execute().body();
            if (ObjectUtil.isNotEmpty(response)) {
                JSONObject result = JSON.parseObject(response);
                if (result.containsKey("code")) {
                    if (result.getIntValue("code") == 200) {
                        if (result.containsKey("data")) {
                            keyCount = 0;
                            return result.getString("data");
                        }
                    } else {
                        try {
                            return count4GenerateKey();
                        } catch (Exception e) {
                            log.error("[重构鉴权缓冲异常] -> {}", e.getMessage());
                        }
                    }
                } else {
                    try {
                        return count4GenerateKey();
                    } catch (Exception e) {
                        log.error("[重构鉴权缓冲异常] -> {}", e.getMessage());
                    }
                }
            } else {
                try {
                    return count4GenerateKey();
                } catch (Exception e) {
                    log.error("[重构鉴权缓冲异常] -> {}", e.getMessage());
                }
            }
        } catch (Exception e) {
            log.error("[请求异常] -> {}", e.getMessage());
            try {
                return count4GenerateKey();
            } catch (Exception ex) {
                log.error("[重构鉴权缓冲异常] -> {}", ex.getMessage());
            }
        }
        return null;
    }


    private static int entityCount = 0;
    private final int entityMax = 6;
    private JSONArray count4GetEntitys() throws Exception {
        if (entityCount >= entityMax) {
            entityCount = 0;
            log.error("[超出最大数据请求次数] -> 单次请求上限：{}", entityMax);
            return null;
        }
        ++entityCount;
        log.warn("[获取失败] -> {}次", entityCount);
        Thread.sleep(3000);
        return getEntitys();
    }

    /**
     * 获取设备信息
     * @param
     * @return
     */
    private JSONArray getEntitys() {
        String authorization = generateKey();
        if (ObjectUtil.isNotEmpty(authorization)) {
            try {
                String response = HttpRequest.post(new StringBuffer(apiAddress).append(getEntitysAction).toString())
                        .header("Authorization", authorization).execute().body();
                if (ObjectUtil.isNotEmpty(response)) {
                    JSONObject result = JSON.parseObject(response);
                    if (result.containsKey("code")) {
                        if (result.getIntValue("code") == 200) {
                            if (result.containsKey("data")) {
                                entityCount = 0;
                                return result.getJSONArray("data");
                            }
                        } else {
                            try {
                                return count4GetEntitys();
                            } catch (Exception e) {
                                log.error("[重构请求缓冲异常] -> {}", e.getMessage());
                            }
                        }
                    } else {
                        try {
                            return count4GetEntitys();
                        } catch (Exception e) {
                            log.error("[重构请求缓冲异常] -> {}", e.getMessage());
                        }
                    }
                } else {
                    try {
                        return count4GetEntitys();
                    } catch (Exception e) {
                        log.error("[重构请求缓冲异常] -> {}", e.getMessage());
                    }
                }
            } catch (Exception e) {
                log.error("[获取数据请求异常] -> {}", e.getMessage());
                try {
                    return count4GetEntitys();
                } catch (Exception ex) {
                    log.error("[重构请求缓冲异常] -> {}", ex.getMessage());
                }
            }
        }
        return null;
    }

    /**
     * 执行对接上传
     */
    private void execute() {
        JSONArray array = getEntitys();
        if (ObjectUtil.isNotEmpty(array) && array.size() > 0) {
            array.forEach(json -> {
                log.info("[预推送DTO] -> {}", json);
                try {
                    JSONObject entity = JSONObject.parseObject(JSONObject.toJSONString(json));
                    String hjText = HJ212Util.getHJString(entity);
                    log.info("[预推送HJ212] -> {}", hjText);
                    String result = SocketUtil.sendMessage(host, port, hjText);
                } catch (Exception e) {
                    log.error("[HJ212格式化异常] -> {}", e.getMessage());
                }
            });
        }
    }

    public void initExecute() {
        log.info("[执行HJ数据上传] -> {}", new Date());
        this.execute();
        log.info("");
    }

    public void doit() {
        initExecute();
    }

}
